package com.atguigu.order.Service;
import java.math.BigDecimal;
import java.util.Arrays;

import com.atguigu.order.Feign.ProductFeignClient;
import com.atguigu.order.bean.Order;
import com.atguigu.product.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService{

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private LoadBalancerClient loadBalancerClient;//负载均衡客户端

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public Order createOrder(Long userId, Long productId) {
        //Product product = productFeignClient.getProductById(productId);
        //使用RestTemplate实现负载均衡
        //Product product = getProductFromRemqteWithLoadBalanceAnnotation(productId);
        //使用feignClient实现远程调用
        Product product = productFeignClient.getProductById(productId);
        Order order = new Order();
        order.setId(1L);
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        //order.setTotalAmount(BigDecimal.valueOf(0));
        order.setUserId(userId);
        order.setNickName("zhangsan");
        order.setAddress("尚硅谷");
        order.setProductList(Arrays.asList(product));
        return order;
    }

    //负载均衡发送请求
    public Product getProductFromRemoteWithLoadBalancer(Long productId){
        //1.获取服务实例
        ServiceInstance choose = loadBalancerClient.choose("service-product");
        //2.获取服务实例的uri
        String url = "http://"+choose.getHost()+":"+choose.getPort()+"/product/"+productId;
        log.info("请求地址：{}",url);
        //3.发送请求
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    //进阶基于注解的负载均衡
    private Product getProductFromRemqteWithLoadBalanceAnnotation(Long productId) {
        String url="http://service-product/product/"+productId;
        //给远程发送请求；service-product会被动态替换
        Product product = restTemplate.getForObject(url,Product.class);
        return product;
    }


}
